package com.jiajia.study.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiajia.common.utils.PageUtils;
import com.jiajia.common.utils.Query;
import com.jiajia.study.product.dao.CategoryDao;
import com.jiajia.study.product.dto.CategoryDTO;
import com.jiajia.study.product.entity.CategoryEntity;
import com.jiajia.study.product.service.CategoryBrandRelationService;
import com.jiajia.study.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    @Lazy
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryDTO> listWithTree() {
        List<CategoryEntity> list = this.list();

        List<CategoryDTO> categoryDTOS =BeanUtil.copyToList(list, CategoryDTO.class);

        if(null == categoryDTOS || categoryDTOS.isEmpty()){
//            throw new RuntimeException("没有数据");
            return categoryDTOS;
        }

        List<CategoryDTO> result = categoryDTOS.stream()
                .filter(categoryDTO -> categoryDTO.getParentCid() == 0)
                .map(categoryDTO -> {
                    categoryDTO.setChildren(getChildren(categoryDTO, categoryDTOS));
                    return categoryDTO;
                })
                .sorted((item1,item2) -> (item1.getSort() == null ? 0  : item1.getSort()) - (item2.getSort() == null ? 0  : item2.getSort()))
                .collect(Collectors.toList());


        return result;
    }

    @Override
    public void batchDelete(Long[] catIds) {
        // todo : 是否被别的地方引用
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId,paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[paths.size()]);
    }

    @Override
    @Transactional
    public void updateInfoById(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategoryByCategoryId(category.getCatId(),category.getName());

    }

    /**
     * 递归查询父类节点
     * @param catelogId 节点id
     * @param paths     路径保存
     * @return          路径列表
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if(null != categoryEntity && 0 != categoryEntity.getParentCid() ){
            findParentPath(categoryEntity.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 递归查找子节点
     * @param categoryDTO       当前节点
     * @param categoryDTOS      所有节点
     * @return                  返回所有子节点
     */
    private List<CategoryDTO> getChildren(CategoryDTO categoryDTO, List<CategoryDTO> categoryDTOS) {
        return categoryDTOS.stream()
                .filter(item -> categoryDTO.getCatId().equals(item.getParentCid()))
                .map(item ->{
                    item.setChildren(getChildren(item, categoryDTOS));
                    return item;
                })
                .sorted((item1,item2) -> (item1.getSort() == null ? 0  : item1.getSort()) - (item2.getSort() == null ? 0  : item2.getSort()))
                .collect(Collectors.toList());
    }

}
